//携带参数获取
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == variable) {
      return decodeURI(pair[1]);
    }
  }
  return false;
}
//卡片文字变更
function contentChange(model) {
  if (model == 'total') {
    $('.detail-title').html(
      'Reaching all of the stages of the sleep cycle is crucial to your health and well-being.'
    );
    $('.detail-content').html(
      "The stages include light and deep sleep. Light sleep is periods when it's easier to wake up while deep sleep is in many ways more restorative. Together the stages make up the sleep cycle which works to heal and restore the body."
    );
  } else if (model == 'deep') {
    $('.detail-title').html(
      'The average healthy adult gets roughly 1 to 2 hours of deep sleep per 8 hours of nightly sleep.'
    );
    $('.detail-content').html(
      "Deep Sleep is when the body reaches a point of relaxation, when the body is healing and restoring energy, the immune system is energized, and the brain goes through the necessary exercises to consolidate memory, learn and process emotions. It's is the 4th Stage of the sleep cycle."
    );
  } else if (model == 'light') {
    $('.detail-title').html(
      'Light sleep initiates your sleep cycle and acts as a transition to deeper sleep stages.'
    );
    $('.detail-content').html(
      'During this stage your muscles begin to relax, your heart rate and breathing slow down, and you wake up easily. During light sleep, you can expect the following: muscles relax and may jerk.'
    );
  } else if (model == 'heart') {
    $('.detail-title').html(
      "Your resting heart rate is the number of times your heart beats per minute when you're at rest. "
    );
    $('.detail-content').html(
      "A good time to check it is in the morning after you've had a good night's sleep. For most of us, between 60 and 100 beats per minute (bpm) is normal. The rate can be affected by factors like stress, anxiety, hormones, medication, and how physically active you are."
    );
  } else if (model == 'breath') {
    $('.detail-title').html(
      'Respiratory rate, or breathing rate, is the number of breaths you take per minute.'
    );
    $('.detail-content').html(
      'A typical respiratory rate for healthy adults is 12–20 breaths per minute. Tracking your respiratory rate trends over time allows you to spot an abnormally high or low rate.'
    );
  } else if (model == 'move') {
    $('.detail-title').html(
      'In the span of a week, the average person tosses 37 to 40 times each night.'
    );
    $('.detail-content').html(
      'Tracking these movements will allow you to understand your sleep patterns. Fragmented or interrupted sleep can lead to daytime consequences, such as fatigue and trouble concentrating the next day. Understanding these conditions is a helpful first step to finding relief.'
    );
  } else if (model == 'hrv') {
    $('.detail-title').html(
      'HRV measures the time variation between successive heartbeats. '
    );
    $('.detail-content').html(
      'Keeping track of your heart rate variability metrics can provide insights, such as understanding how outside factors could be having a negative impact. Steadily rising numbers will indicate progress in your fitness, while a decline from your normal averages may highlight a need to address an underlying issue such as sleep or stress.'
    );
  } else if (model == 'snore') {
    $('.detail-title').html(
      'Habitual snoring can lead to disturbed sleep or be a sign of other complications.'
    );
    $('.detail-content').html(
      "Tracking your snoring activity can help inform needed next steps. Snoring can often be reduced with lifestyle changes to include raising the head of your bed. For this to work, it's important to raise the whole mattress and not just use more pillows."
    );
  } else {
    $('.detail-title').html(
      'Track the number of times you get out of bed at night to monitor changes in your health. '
    );
    $('.detail-content').html(
      'Increased frequency may be caused by: restless leg syndrome, sleep apnea, increased urination, medication, sleep disorders, pain, or other issues.  Getting out of bed at night can lead to increased fall risks. If you notice a change in this health metric you may want to contact your physician.'
    );
  }
}
//时间格式化
function dateformat(date, flag, label) {
  var time = new Date(date);
  var year = time.getFullYear();
  if (flag == 1) {
    year = time.getFullYear() - 1;
  }
  if (flag == 2) {
    year = time.getFullYear() + 1;
  }
  var mon = time.getMonth() + 1;
  mon = mon < 10 ? '0' + mon : mon;
  var day = time.getDate();
  day = day < 10 ? '0' + day : day;
  var hour = time.getHours();
  hour = hour > 9 ? hour : '0' + hour;
  var min = time.getMinutes();
  min = min > 9 ? min : '0' + min;
  var second = time.getSeconds();
  second = second > 9 ? second : '0' + second;
  if (label == 1) {
    return year + '/' + mon + '/' + day + ' ' + hour + ':' + min + ':' + second;
  } else if (label == 2) {
    return year + '-' + mon + '-' + day;
  } else if (label == 3) {
    if (hour > 12) {
      hour = hour - 12;
      re = hour + ' PM';
      hour = hour + ':' + min + ' PM';
    } else {
      if (hour == 0) {
        hour = 12;
        re = hour + ' AM';
        hour = parseInt(hour) + ':' + min + ' AM';
      } else {
        re = hour + ' AM';
        hour = parseInt(hour) + ':' + min + ' AM';
      }
    }
    return hour;
  } else if (label == 4) {
    console.log('hour', hour);
    if (hour > 12) {
      hour = hour + ':' + min;
    } else {
      if (hour == 0) {
        hour = 0;
        // re = hour + ' AM';
        hour = hour + ':' + min;
      } else {
        // re = hour + ' AM';
        hour = time.getHours() + ':' + min;
      }
    }
    return hour;
  } else {
    return year + '/' + mon + '/' + day + ' 00:00:00';
  }
}
//睡眠时长显示
function showduration(duration, deep, light, awake) {
  let a = (deep + light) % 60;
  let b = (deep + light - a) / 60;
  if (deep + light > 60) {
    $('#title-text-day').html(b + ' ' + languageData.lab_13 + " " + a + ' min');
  } else {
    $('#title-text-day').html(a + ' min');
  }
  let c = deep % 60;
  let d = (deep - c) / 60;
  if (deep > 60) {
    $('#deep-data').html(d + ' ' + languageData.lab_13 + " " + c + ' min');
  } else {
    $('#deep-data').html(c + ' min');
  }
  let e = light % 60;
  let f = (light - e) / 60;
  if (light > 60) {
    $('#light-data').html(f + ' ' + languageData.lab_13 + " " + e + ' min');
  } else {
    $('#light-data').html(e + ' min');
  }
  let g = awake % 60;
  let h = (awake - g) / 60;
  if (awake > 60) {
    $('#awake-data').html(h + ' ' + languageData.lab_13 + " " + g + ' min');
  } else {
    $('#awake-data').html(g + ' min');
  }
}
//打鼾干预数据处理
function snorehandle(sleep, wake, data, arr1) {
  let x = [];
  let s = [];
  data = eval('(' + data + ')');
  sleep = sleep.replace(/-/g, '/');
  wake = wake.replace(/-/g, '/');
  let start = new Date(sleep).getTime();
  let end = new Date(wake).getTime();
  let interval = (end - start) / 3600000;

  for (let i = 0; i < interval + 1; i++) {
    let x_0 = [];
    let time = i * 3600000 + start;
    x_0[0] = time;
    x_0[1] = 0;
    x.push(x_0);
  }
  s = x;
  for (let j = 1; j < s.length; j++) {
    let a = s[j - 1][0];
    let a2 = s[j][0];
    for (let k = 0; k < data.length; k++) {
      let b = new Date(data[k].replace(/-/g, '/')).getTime();
      if (a < b && b < a2) {
        let x_1 = [];
        x_1[0] = b;
        x_1[1] = 1;
        x.splice(j, 0, x_1);
      }
    }
  }
  return x;
}
//采样数据收集
function getcollect(data) {
  let a = '';
  if (data.sleep_time) {
    a = data.sleep_time.replace(/-/g, '/');
  }
  let b = '';
  if (data.wake_time) {
    b = data.wake_time.replace(/-/g, '/');
  }
  var start = new Date(a);
  var end = new Date(b);
  var date = new Date();
  let size = 60 * 1000 * 5; //5分钟间隔
  let long = (end.getTime() - start.getTime()) / size;

  let length = Math.round(long);
  while (this.collect.length <= length) {
    let d = new Date(start.getTime());
    collect.push(dateformat(d, 0, 3));
    collect2.push(start.getTime());
    start = new Date(start.getTime() + size);
  }
}
//rem根元素设置
function fontset() {
  var baseFontSize = 100;
  var baseWidth = 375;
  var set = function () {
    var clientWidth = document.documentElement.clientWidth || window.innerWidth;
    var rem = 100;
    if (clientWidth >= 768) {
    }
    if (clientWidth != baseWidth) {
      rem = Math.floor((clientWidth / baseWidth) * baseFontSize);
    }
    document.querySelector('html').style.fontSize = rem + 'px';
  };
  set();
  window.addEventListener('resize', set);
}
//图标字体大小设置
function getDpr() {
  clientWidth = document.documentElement.clientWidth || window.innerWidth;
  if (clientWidth <= 667) {
    return 8.5;
  }
  if (clientWidth <= 812 && clientWidth > 667) {
    return 10;
  }
  if (clientWidth <= 1024 && clientWidth > 812) {
    return 12;
  }
  if (clientWidth <= 1680 && clientWidth > 1024) {
    return 16;
  }
}
//首字母大写
function capitalize(str) {
  return str.replace(/(^|\s)([a-z])/g, function (m, p1, p2) {
    return p1 + p2.toUpperCase();
  });
}
//不同模块切换时卡片显示的渲染
function movecheck(index) {
  if (index == 0) {
    if (
      model == 'move' ||
      model == 'snore' ||
      model == 'outbed' ||
      model == 'hrv'
    ) {
      $('.card_2').css({ display: 'none' });
    } else if (model == 'deep' || model == 'light') {
      $('.card3_1').css({ display: 'none' });
    }
  } else if (index == 1 || index == 2 || index == 3) {
    if (
      model == 'move' ||
      model == 'snore' ||
      model == 'outbed' ||
      model == 'hrv'
    ) {
      $('.card_2').css({ display: 'block' });
    } else if (model == 'deep' || model == 'light') {
      $('.card3_1').css({ display: 'block' });
    }
  } else {
  }
}
function sleep_x_handler(data) {
  awake = [];
  light = [];
  deep = [];
  time = [];
  let a = data.split(',');
  a.filter((item) => {
    let tempvalue = item.charAt(item.length - 1);
    if (tempvalue == 1) {
      awake.push(0);
      light.push(0);
      deep.push(parseInt(item.substring(item.length - 1, item.length)));
    } else if (tempvalue == 2) {
      awake.push(0);
      light.push(parseInt(item.substring(item.length - 1, item.length)));
      deep.push(0);
    } else {
      awake.push(3);
      light.push(0);
      deep.push(0);
    }
  });
  for (let i of a) {
    time.push(i.substring(0, i.length - 2).replace(/-/g, '/'));
  }
  let x = [];
  let y = [];
  let z = [];
  o = [];
  for (let i = 0; i < time.length - 1; i++) {
    let t =
      (new Date(time[i + 1]).getTime() - new Date(time[i]).getTime()) / 120000;
    for (let j = 0; j <= t - 1; j++) {
      let x_0 = [];
      let y_0 = [];
      let z_0 = [];
      let o_0 = [];
      x_0[0] = new Date(time[i]).getTime() + j * 120000;
      x_0[1] = awake[i];
      y_0[0] = new Date(time[i]).getTime() + j * 120000;
      y_0[1] = light[i];
      z_0[0] = new Date(time[i]).getTime() + j * 120000;
      z_0[1] = deep[i];
      o_0[0] = new Date(time[i]).getTime() + j * 120000;
      o_0[1] = 0;
      x.push(x_0);
      y.push(y_0);
      z.push(z_0);
      o.push(o_0);
    }
  }
  x.push([new Date(time[time.length - 1]).getTime(), awake[awake.length - 1]]);
  y.push([new Date(time[time.length - 1]).getTime(), light[light.length - 1]]);
  z.push([new Date(time[time.length - 1]).getTime(), deep[deep.length - 1]]);
  o.push([new Date(time[time.length - 1]).getTime(), 0]);
  awake = x;
  light = y;
  deep = z;
}
//日报睡眠分期x轴2端坐标处理
function handletime(time, index, timetype) {
  let temparr = [];
  if (time.indexOf(':')) {
    temparr = time.split(':');
    //如果为12小时制
    if (timetype == 12) {
      //时间是PM时间
      if (temparr[1].indexOf('PM') != -1) {
        //是入睡时间
        if (index == 1) {
          return temparr[0] + 'PM';
        } else {
          return parseInt(temparr[0]) + 1 + 'PM';
        }
      } else {
        if (index == 1) {
          return temparr[0] + 'AM';
        } else {
          return parseInt(temparr[0]) + 1 + 'AM';
        }
      }
    } else {
      if (index == 1) {
        return temparr[0] + ':00';
      } else {
        let tempnum = parseInt(temparr[0]) + 1;
        if (tempnum == 24) {
          return '0:00';
        } else {
          return parseInt(temparr[0]) + 1 + ':00';
        }
      }
    }
  }
}
//日报睡眠分期x轴中间坐标处理
function handletime2(time1, time2, timetype) {
  let temparr = [];
  let truth_1 = time1.indexOf('PM') != -1 || parseInt(time1) > 12; //入睡时间是否在下午
  let truth_2 = time2.indexOf('PM') != -1 || parseInt(time2) > 12; //醒来时间是否在下午
  let temp_1 = parseInt(time1.slice(0, time1.length - 2));
  let temp_2 = parseInt(time2.slice(0, time2.length - 2));
  let longth = 0;
  let longth_1 = '';
  let longth_2 = '';
  let longth_3 = '';
  console.log('truth_1', truth_1);
  console.log('truth_2', truth_2);
  //前后坐标是否都为PM或AM
  if (truth_1 == truth_2) {
    //间隔时间
    longth = ((temp_2 - temp_1) / 3).toFixed(1);
  } else {
    if (timetype == 12) {
      longth = ((12 + temp_2 - temp_1) / 3).toFixed(1);
    } else {
      longth = ((24 + temp_2 - temp_1) / 3).toFixed(1);
    }
  }
  console.log('longth', longth);
  longth_1 = parseInt(longth.split('.')[0]);
  longth_2 = (parseInt(longth.split('.')[1]) * 60) / 10;
  longth_3 = ((longth * 2).toFixed(1).split('.')[1] * 60) / 10;
  let finaltime_1 = handletime3(longth_2, timetype);
  let finaltime_2 = handletime3(longth_3, timetype);
  let finalarr = [];
  let time3 = temp_1 + parseInt(longth_1);
  console.log('time3', time3)
  let time4 = 0;
  if (parseInt(longth.split('.')[1]) > 5) {
    time4 = time3 + parseInt(longth_1) + 1;
  } else {
    time4 = time3 + parseInt(longth_1);
  }
  if (timetype == 12) {
    //是否为12小时制
    if (time3 >= 12) {
      time3 = time3 - 12 + ':' + finaltime_1 + (truth_1 ? 'AM' : 'PM');
      time4 = time4 - 12 + ':' + finaltime_2 + (truth_1 ? 'AM' : 'PM');
    } else {
      time3 = time3 + ':' + finaltime_1 + (truth_1 ? 'PM' : 'AM');
      time4 = time4 + ':' + finaltime_2 + (truth_1 ? 'PM' : 'AM');
    }
    finalarr = [time3, time4];
    console.log('finalarr', finalarr);
    return finalarr;
  } else {
    if (time3 > 24) {
      time3 = time3 - 24 + ':' + finaltime_1;
    } else {
      time3 = time3 + ':' + finaltime_1;
    }
    if (time4 > 24) {
      time4 = time4 - 24 + ':' + finaltime_2;
    } else {
      time3 = time3 + ':' + finaltime_1;
    }
    finalarr = [time3, time4];
    console.log('finalarr', finalarr);
    return finalarr;
  }
}
//判断15分钟间隔刻度
function handletime3(time) {
  console.log('time11111', time);
  //与15分钟间隔相差的时间(绝对值)
  let abs_0 = Math.abs(0 - time);
  let abs_1 = Math.abs(15 - time);
  let abs_2 = Math.abs(30 - time);
  let abs_3 = Math.abs(45 - time);
  let abs_4 = Math.abs(60 - time);
  let arr = [abs_0, abs_1, abs_2, abs_3, abs_4];
  let min = Math.min(...arr);
  let index = arr.indexOf(min);
  let finaltime = 0;
  if (index == 0 || index == 1) {
    //0-15或15-30靠近15
    finaltime = 15;
  } else if (index == 2) {
    //30
    finaltime = 30;
  } else {
    finaltime = 45;
  }
  return finaltime;
}
//报告数据处理渲染函数
function reRender(data) {
  let temp = {}
  //判断分段数组的位置
  temp = copyArr(data)
  //处理分段数组
  //重新生成新的数组
  //重新渲染图表
  return temp
}
//复制两个符合要求的数组
function copyArr(arr) {
  console.log('arr====>', arr)
  let obj = {}
  obj.hasdata = []
  obj.nodata = []
  let startHandleFlag = false
  arr.forEach((item, index) => {
    if (item != '-') {
      startHandleFlag = true
    }
    if (startHandleFlag) {
      if (item != "-") {
        obj.hasdata.push(item)
        obj.nodata.push('-')
      }
      if (item == "-") {
        obj.hasdata.push('-')
        obj.nodata.push(0)
      }
    } else {
      obj.hasdata.push("-")
      obj.nodata.push('-')
    }
  });
  obj = Arithmetic(arr, obj)
  //console.log('objARR=======>', obj)
  return obj
}
//等差数列段落生成
function Arithmetic(arr, objarr) {
  let obj = objarr
  let startIndex = null
  let endIndex = 0
  let startHandleFlag = false  //首个非零值开始处理数据
  let startFlag = false //开始获取片段
  let endFlag = false //片段获取结束，开始处理
  //判断无报告片段位置
  arr.forEach((item, index) => {
    if (item != "-") {
      startHandleFlag = true
    }
    if (startHandleFlag) {
      if (index + 1 <= arr.length - 1) {
        if (arr[index + 1] == "-" && arr[index] != "-") {
          // console.log('test2222')
          startFlag = true
        }
        if (arr[index] == "-" || arr[index + 1] == "-") {
          if (arr[index] == "-") {
            obj.nodata[index + 1] = obj.hasdata[index + 1]
            endIndex = index + 1
          }
          if (arr[index + 1] == "-") {
            obj.nodata[index] = obj.hasdata[index]
            if (startIndex == null) {
              startIndex = index
            }
          }
        }
        if (arr[index] == "-" && arr[index + 1] != "-") {
          endFlag = true
        }
        //console.log('startIndex&&endIndex==>', startIndex, endIndex, endFlag)
        if (endFlag) {
          //console.log('nodata===>', obj.nodata, arr, startIndex, endIndex)
          if (endIndex != 0) {
            let tempCount = 0
            let bigFlag = (obj.nodata[startIndex] - obj.nodata[endIndex] > 0) ? true : false  //开始比结束值大为true,否则false
            tempCount = Math.abs(obj.nodata[startIndex] - obj.nodata[endIndex]) / (endIndex - startIndex)  //等差差值
            //console.log('tempCount===>', tempCount)
            for (let i = startIndex + 1; i <= endIndex - 1; i++) {
              if (bigFlag) {  //开始值大
                obj.nodata[i] = obj.nodata[startIndex] - tempCount * (i - startIndex)
              } else {  //开始值小
                obj.nodata[i] = obj.nodata[startIndex] + tempCount * (i - startIndex)
              }
            }
            startIndex = null
            endIndex = 0
            startFlag = false
            endFlag = false
          }
        }
      }
    }
  })
  return obj
}

